<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="/favicon.ico">
    <script src="./js/jquery-3.3.1.js"></script>
    <title>颗粒分析系统</title>
    <style>
        body {}
        .sub {border:    1px black solid}
        table tr td.sub.left  {width: 400px; height: 450px; }
        table tr td.sub.right {width: 700px; height: 450px;}
        table tr td.sub.top  {}
        table tr td.sub.down {}


        .cameras {display:flex; flex-direction: row; align-items: center}
        .camera {cursor: pointer; padding: 0px 15px 0px 15px; color: gray}
        .camera:hover {background-color: gray; color: white}
        .camera.selected {border: 1px black solid; background-color: blue; color: yellow}

        #time_refresh {width: 30px; text-align: right}

        #last_img {}
        #last_img img {width: 600px; height: 450px}

        #query {}
        #query.pictures {}
        #query.buttons {}

        #times {display:flex; flex-direction: column; justify-content: center}
        .time_buttons {display:flex; flex-direction: row; justify-content: center; flex-grow:0; border-bottom: 1px black solid}
        .time_button {margin-top: 10px}
        .time_query {flex-grow:0; display:flex; flex-direction: row; justify-content: center; }
        #times input {width: 150px}
        #query_result {width: 900px; height: 400px}

        #last_chart {width: 600px; min-width: 310px; height: 400px; margin: 0 auto; }
        #btn_refresh {padding: 5px 5px 5px 5px;}

        #msg {text-align: center; margin-top: 10px}        #
    </style>
</head>
<body>
<div style="display:flex; flex-direction: column; align-items: center; padding: 0 10px 0 10px">
    <div class="cameras">
        <div class="camera">
            click me
        </div>
    </div>
    <div id="pane">
        <table id="main" cellspacing="0">
            <tr><td class="sub left top">
                <div id="last_img"><img></div>
            </td><td class="sub right top">
            </td></tr>
            <tr><td class="sub left down">
                <div id="last_chart"></div>
                <div style="display:flex; justify-content: center"> 每<input id="time_refresh" value="5"> &nbsp;秒&nbsp; <button id="btn_refresh">自动显示最后一张图片</button></div>
            </td><td class="sub right down">
                <div  id="times">
                    <div class="time_query">
                        开始时间:&nbsp;<input id="start" placeholder="2023-1-14 8:19:0"> &nbsp; 结束时间:&nbsp;
                        <input id="end" placeholder="2023-1-14 8:20:0">
                        <button id="btn_query">查询</button>
                    </div>
                    <div class="time_buttons"></div>
                </div>
                <div id="query_result"></div>
            </td></tr>
        </table>
    </div>
    <div id="msg"></div>
</div>

<script src="chart/highcharts.js"></script>
<script src="chart/modules/exporting.js"></script>
<script src="chart/modules/series-label.js"></script>

<script type="text/javascript">
    function call_api(url, data, func) {
        $("#msg").html("calling " + url);
        $.ajax({
            type: "GET",
            url: url,
            data: data,
            contentType: "json",
            success: function(result) {
                if(result.err_code == 0) {
                    $("#msg").html("<div style='color: gray'>Done!</div>");
                    func(result.result);
                } else {
                    $("#msg").html("<div style='color: red'>" + result.err_msg + "</div>");
                }
            },
            error: function(e) {
                $("#msg").val("Error!");
                alert("异常: " + e);
            }
        });
    }

    var time_buttons = [{
        name: '最后5分钟',
        time: 5*60,
        mod:  0
    }, {
        name: '最后10分钟',
        time: 10*60,
        mod:  0
    }, {
        name: '最后20分钟',
        time: 20*60,
        mod:  0
    }, {
        name: '最后半小时',
        time: 30*60,
        mod:  0
    }, {
        name: '最后1小时',
        time: 60*60,
        mod:  0
    }, {
        name: '最后12小时',
        time: 12*60*60,
        mod:  0
    }, {
        name: '最后24小时',
        time: 24*60*60,
        mod:  0
    }, {
        name: '最后48小时',
        time: 48*60*60,
        mod:  0
    }, {
        name: '今天',
        time: 0,
        mod: 24*60*60
    }, {
        name: '昨天至今',
        time: 24*60*60,
        mod: 24*60*60
    }, {
        name: '本周',
        time: 0,
        mod: 7*24*60*60
    }, {
        name: '上周至今',
        time: 7*24*60*60,
        mod: 7*24*60*60
    }];

    function show_time_buttons() {
        var html = "";
        for(var i in time_buttons) {
            var tb = time_buttons[i];
            html += "<button class='time_button' time='" + tb.time + "' mod='" + tb.mod + "'>" + tb.name + "</button>";
        }
        $('.time_buttons').html(html);
        $('.time_button').click(function() {
            query_on_time($(this).attr('time'), $(this).attr('mod'));
        });
    }

    show_time_buttons();

    var current_camera_id = -1;

    function fill_cameras(cameras) {
        var html = "";
        for(var i in cameras) {
            var camera = cameras[i];
            html += "<div class='camera' camera_id='" + camera.id + "'>" + camera.name + "</div>";
        }
        $(".cameras").html(html);
        $(".camera").click(function() {
            show_camera($(this).attr("camera_id"));
        });
        show_camera(cameras[0].id);
    }

    function show_camera(camera_id) {
        if(current_camera_id >= 0) {
            $(".camera[camera_id='" + current_camera_id + "']").removeClass("selected");
        }
        current_camera_id = camera_id;
        $(".camera[camera_id='" + camera_id + "']").addClass("selected");
        refresh();
    }

    var show_last = true;
    function fill_last_chart(data) {
        fill_distribute(data.distribute, data.titles);
    }

    function fill_distribute(distribute, titles) {
        if(distribute == null) {
            $("#msg").text("没有找到图片");
            $("#last_img img").attr("src", "/static/favicon.ico");
            return;
        }
        $("#last_img img").attr("src", "/api/particles/download_img?img_id=" + distribute.img_id);
        Highcharts.chart('last_chart', {
            chart: {
                type: 'column'
            },
            title: {
                text: '照片上的颗粒分布'
            },
            subtitle: {
                text: distribute.img_time
            },
            xAxis: {
                categories: titles,
                crosshair: true
            },
            yAxis: {
                min: 0,
                max: 100.0,
                title: {
                    text: '比例'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                    '<td style="padding:0"><b>{point.y:.1f}%</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: '占比',
                data: get_props(distribute)
            }]
        });
        $("#msg").text("");
    }

    function get_props(distribute) {
        var props = [];
        for(var i = 0; i < 5; i++) {
            props.push(distribute["prop" + i] * 100);
        }
        return props;
    }


    function refresh() {
        if(show_last) {
            call_api("/api/particles/get_last_distribute", {camera_id: current_camera_id}, fill_last_chart);
        }
    }

    function fill_query_result(data) {
        Highcharts.chart('query_result', {
            chart: {
                type: 'spline'
            },
            title: {
                text: '颗粒分布线图'
            },

            subtitle: {
                text: ''
            },

            xAxis: {
                categories: get_img_times(data.distributes),
                title: {
                    text: '时间'
                }
            },
            yAxis: {
                min: 0,
                max: 100.0,
                title: {
                    text: '比例'
                }
            },
//            tooltip: {
//                headerFormat: '<b>{series.name}</b><br>',
//                pointFormat: '{point.x:%e. %b}: {point.y:.2f}%'
//            },

            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle'
            },

            plotOptions: {
                series: {
                    cursor: 'pointer',
                    events: {
                        click: function(e) {
                            show_last = false;
                            fill_distribute(data.distributes[e.point.index], data.titles);
                        }
                    }
                },
                spline: {
                    marker: {
                        enabled: true
                    }
                }
            },

            series: get_serials(data),

            responsive: {
                rules: [{
                    condition: {
                        maxWidth: 500
                    },
                    chartOptions: {
                        legend: {
                            layout: 'horizontal',
                            align: 'center',
                            verticalAlign: 'bottom'
                        }
                    }
                }]
            }

        });
    }

    function get_serials(data) {
        var result = [];
        for(var i = 0; i < data.titles.length; i++) {
            var rec = {};
            rec.name = data.titles[i];
            rec.data = get_column_props(data.distributes, i);
            result.push(rec);
        }
        return result;
    }

    function get_img_times(distributes) {
        var result = [];
        for(var i = 0; i < distributes.length; i++) {
            result.push(distributes[i]['img_time']);
        }
        return result;
    }

    function get_column_props(distributes, prop_index) {
        var result = [];
        for(var i = 0; i < distributes.length; i++) {
            var d = distributes[i];
            result.push(d['prop' + prop_index] * 100);
        }
        return result;
    }

    function query() {
        var dt_start = $("#start").val();
        var dt_end = $("#end").val();
        call_api("/api/particles/query", {
                        camera_id: current_camera_id,
                        start: dt_start,
                        end: dt_end
                 }, fill_query_result);
    }

    function to2(value) {
        return (value < 10 ? "0" : "") + value;
    }

    function query_on_time(seconds, mod) {
        var t = (new Date()).getTime();

        t -= seconds * 1000;
        if(mod == 0) {
            t = new Date(t);
        } else {
            var delta = 8 * 60 * 60 * 1000
            mod *= 1000;
            t = Math.floor((t + delta) / mod) * mod - delta;
            t = new Date(t);
        }
        t = t.getFullYear() + "-" + to2(t.getMonth()+1) + "-" + to2(t.getDate()) + " " +
                to2(t.getHours()) + ":" + to2(t.getMinutes()) + ":" + to2(t.getSeconds());
        $("#start").val(t);
        $("#end").val("");
        query();
    }

    var interval_flag = null;
    function btn_refresh_click() {
        if(interval_flag != null) {
            clearInterval(interval_flag);
        }
        var seconds = parseInt($('#time_refresh').val());
        show_last = true;
        interval_flag = setInterval(refresh, seconds * 1000);
        refresh();
    }

    $("#btn_refresh").click(btn_refresh_click);
    $("#btn_query").click(query);

    call_api("/api/camera/get_cameras", {}, function(cameras) {
        fill_cameras(cameras);
        btn_refresh_click();
    });

</script>

</body>
</html>